package com.tom.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.tom.constants.BaseConstants;
import com.tom.domain.Login;
import com.tom.dto.LoginAndMealIdDto;
import com.tom.exception.GloblException;
import com.tom.mapper.LoginMapper;
import com.tom.service.ILoginService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tom.service.IMealService;
import com.tom.util.AjaxResult;
import com.tom.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.security.GeneralSecurityException;
import java.util.Map;

/**
 * <p>
 * 登录表 服务实现类
 * </p>
 *
 * @author pengh.liu
 * @since 2021-11-22
 */
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, Login> implements ILoginService {
    // 对密码进行加密的操作
//    @Autowired
//    private PasswordEncoder passwordEncoder;

    @Autowired
    private IMealService mealService;

    //获取密码模式的Token
    public static final String URL_TOKEN_PASSWORD = "http://localhost:1050/oauth/token?client_id=%s&client_secret=%s&grant_type=password&username=%s&password=%s";
    public static final String URL_TOKEN_REFRESH = "http://localhost:1050/oauth/token?client_id=%s&client_secret=%s&grant_type=refresh_token&refresh_token=%s";

    @Override
    public AjaxResult saveLoginAndMeal(LoginAndMealIdDto loginAndMealIdDto) {
        // 参数校验
        Login login = loginAndMealIdDto.getLogin();
        Long mealId = loginAndMealIdDto.getMealId();
        if (login == null){
            throw new RuntimeException("login对象为空");
        }
        if (mealId == null){
            throw new RuntimeException("套餐id为空");
        }
        // 默认初始设置，这些设置防止直接传入login进行修改
        login.setPassword(new BCryptPasswordEncoder().encode(login.getPassword())); // 对密码进行加密
        login.setEnabled(true);
        login.setAccountNonExpired(true);
        login.setAccountNonLocked(true);
        login.setCredentialsNonExpired(true);
        // 保存login
        insert(login);

        // 调用方法保存登录信息和套餐中间表
        mealService.saveRelationWithLogin(mealId,login.getId());
        return AjaxResult.me().setResultObj(login.getId());

    }

    /**
     * 登录的方法
     * @param login
     * @return
     */
    @Override
    public Map<String,String> login(Login login) {
        String clientId = "";
        String secret = "";

        EntityWrapper wrapper = new EntityWrapper();
        wrapper.eq("username", login.getUsername());
        Login selectOne = super.selectOne(wrapper);

        if (selectOne != null){
            if (selectOne.getType() == BaseConstants.Login.LOGIN_BACKGROUND){ // 判断是否为后台用户
                clientId = "admin";
                secret = "123";

            }else if (selectOne.getType() == BaseConstants.Login.LOGIN_FRONTDESK){
                clientId = "website";
                secret = "123";
            }
        }
        String url = String.format(URL_TOKEN_PASSWORD, clientId,
                secret, login.getUsername(), login.getPassword());
        // 发送请求获取token
        Map<String, String> map = HttpUtil.sendPost(url);
        String error_description = map.get("error_description");
        if (error_description != null){
            throw new GloblException("账号或者密码错误");
        }

        return map;
    }

    /**
     * 刷新
     * @param refreshToken
     */
    @Override
    public Map<String, String> refresh(String refreshToken) {
        String url = String.format(URL_TOKEN_REFRESH, "admin",
                "123", refreshToken);
        // 发送请求获取token
        Map<String, String> map = HttpUtil.sendPost(url);
        return map;
    }
}
